package com.stary.music.api.source.kugou;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stary.music.api.vo.MusicInfo;
import com.stary.music.exception.MyMusicException;
import com.stary.music.util.HTTPUtils;
import com.stary.music.util.PropertiesUtils;

/**
 * 酷狗音乐API
 * @author stary
 * @date 2018年6月14日 上午10:40:06
 */
public class KuGouMusic {
	private static final Logger logger=LoggerFactory.getLogger(KuGouMusic.class);
	private static final String PREFIX="kugou.music";	
	private static PropertiesUtils pUtils=null;	 
	static {
		pUtils=new PropertiesUtils();
		pUtils.setKeyPrefix(PREFIX);
	}
	/**
	 * 根据关键词搜索歌曲信息 <br>
	 * 关键词：歌曲名、专辑、歌手 
	 * @param searchRequest
	 * @return
	 */
	public List<MusicInfo> searchMusicList(KuGouSearchRequest searchRequest){
		if(searchRequest.getKeyword()==null || searchRequest.getKeyword().isEmpty()){
			logger.error("缺少参数或出现不能识别的参数");
			throw new MyMusicException("a parameter is missing or unrecognized");
		}
		List<MusicInfo> list=null;
		StringBuffer buffer=new StringBuffer();
		JSONObject searchRequestJSON=(JSONObject) JSONObject.toJSON(searchRequest);
		for (Entry<?, ?> entry : searchRequestJSON.entrySet()) {
			buffer.append("&" + entry.getKey() + "=" + entry.getValue());
		}
		buffer.replace(0, 1, "");
		logger.debug("搜索歌曲信息入参----->>{}",buffer.toString());
		pUtils.setKey("search1");
		try {
			String resp=HTTPUtils.sendGet(pUtils.getStringValue(), buffer.toString());
			logger.debug("搜索歌曲信息出参----->>{}",resp);
			if(!resp.isEmpty()){
				JSONObject respJSON = JSONObject.parseObject(resp);
				if (respJSON.getInteger("status")== 1) {
					String data = respJSON.getString("data");
					JSONObject dataJSON = JSONObject.parseObject(data);
					if (dataJSON.containsKey("info")) {
						list=new ArrayList<MusicInfo>();
						MusicInfo musicInfo=null;
						JSONArray infoJSONArray = dataJSON.getJSONArray("info");
						for (int i = 0; i < infoJSONArray.size(); ++i) {
							String info = infoJSONArray.getString(i);
							JSONObject infoJSON = JSONObject.parseObject(info);
							musicInfo=new MusicInfo();
							// 歌名
							String name = infoJSON.getString("songname");
							musicInfo.setName(name);
							// ID
							String id=infoJSON.getString("audio_id");
							musicInfo.setId(id);
							// 歌手
							String singer = infoJSON.getString("singername");
							musicInfo.setSinger(singer);
							// 专辑
							String album=infoJSON.getString("album_name");
							musicInfo.setAlbum(album);
							// 歌曲详细信息
							String hash = infoJSON.getString("hash");
							musicInfo.setMid(hash);
							pUtils.setKey("src");
							try {
								String songResp=HTTPUtils.sendGet(pUtils.getStringValue(), "r=play/getdata&hash=" + hash);
								if(!songResp.isEmpty()){

									JSONObject songRespJSON = JSONObject.parseObject(songResp);
									if (songRespJSON.getInteger("status")== 1) {
										String songData = songRespJSON.getString("data");
										JSONObject songDataJSON = JSONObject.parseObject(songData);
										// 歌曲外链 
										//String src = songDataJSON.getString("play_url");
										//musicInfo.setSrc(src);
										// 封面
										String cover=songDataJSON.getString("img");
										musicInfo.setCover(cover);
										// 歌手 艺术家
										if(songDataJSON.containsKey("authors")){
											JSONArray authorsJSONArray = songDataJSON.getJSONArray("authors");
											StringBuffer singers = new StringBuffer();
											for (int j = 0; j < authorsJSONArray.size(); j++) {
												String author = authorsJSONArray.getString(j);
												JSONObject authorJSON = JSONObject.parseObject(author);
												singers.append(authorJSON.getString("author_name"));
												if (j < authorsJSONArray.size() - 1) {
													singers.append("/");
												} 
											}
											musicInfo.setSinger(singers.toString());
										}
										// 歌词
										if(searchRequest.getShowLrc()!=0){
											String lyrics = songDataJSON.getString("lyrics");											
											musicInfo.setLyric(lyrics);

										}

									}
								}
							} catch (Exception e) {
								logger.error("获取歌曲详细信息出现异常",e);
							}
							list.add(musicInfo);
						}
					}
				}
			}
		}catch (Exception e) {
			logger.error("搜索歌曲信息出现异常",e);
		}
		return list;
	}
	/**
	 * 获取外链
	 * @param mid -> hash
	 * @return
	 */
	public String getMusicSrc(String mid){
		pUtils.setKey("src");
		String src="";
		try {
			String songResp=HTTPUtils.sendGet(pUtils.getStringValue(), "r=play/getdata&hash=" + mid);
			logger.debug("获取歌曲信息出参----->>{}",songResp);
			if(!songResp.isEmpty()){

				JSONObject songRespJSON = JSONObject.parseObject(songResp);
				if (songRespJSON.getInteger("status")== 1) {
					String songData = songRespJSON.getString("data");
					JSONObject songDataJSON = JSONObject.parseObject(songData);
					// 歌曲外链
					src = songDataJSON.getString("play_url");
				}
			}
		} catch (Exception e) {
			logger.error("获取歌曲外链出现异常",e);
		}
		return src;
	}
	/**
	 * 获取歌词
	 * @param mid -> hash
	 * @return
	 */
	public String getMusicLyric(String mid){
		pUtils.setKey("src");
		String lyric="";
		try {
			String songResp=HTTPUtils.sendGet(pUtils.getStringValue(), "r=play/getdata&hash=" + mid);
			logger.debug("获取歌曲信息出参----->>{}",songResp);
			if(!songResp.isEmpty()){

				JSONObject songRespJSON = JSONObject.parseObject(songResp);
				if (songRespJSON.getInteger("status")== 1) {
					String songData = songRespJSON.getString("data");
					JSONObject songDataJSON = JSONObject.parseObject(songData);
					// 歌曲外链
					lyric = songDataJSON.getString("lyrics");
				}
			}
		} catch (Exception e) {
			logger.error("获取歌曲歌词出现异常",e);
		}
		return lyric;
	}
}
